<template>
  <div>
    <el-select v-model="province" placeholder="选择省份" clearable>
      <el-option v-for="item in areas" :key="item.code" :label="item.name" :value="item.code" />
    </el-select>

    <el-select :disabled="!province" v-model="city" placeholder="选择城市" clearable>
      <el-option v-for="item in selectedCities" :key="item.code" :label="item.name" :value="item.code" />
    </el-select>

    <el-select :disabled="!city" v-model="area" placeholder="选择地区" clearable @change="changeArea">
      <el-option v-for="item in selectedAreas" :key="item.code" :label="item.name" :value="item.code" />
    </el-select>

  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import allAreas from "./pca.json";

const province = ref('')
const city = ref('')
const area = ref('')

const areas = ref(allAreas)

// 省份变化时,城市跟随变化
const selectedCities = computed(() => {
  city.value = '' // 清除
  if (province.value === '') {
    return []
  }
  let cities = areas.value.find(p => p.code === province.value)!.children
  if (cities.length === 1) {
    city.value = cities[0].code
  }
  return cities
})

// 城市变化时,地区跟随变化
const selectedAreas = computed(() => {
  area.value = '' // 清除
  if (city.value === '') {
    return []
  }
  let as = areas.value.find(p => p.code === province.value)!.children.find(c => c.code === city.value)!.children
  return as
})

// 返回选择数据给父组件
let emits = defineEmits(['change'])
let changeArea = () => {
  let p = areas.value.find(p => p.code === province.value)!

  let c = p.children.find(p => p.code === city.value)!

  let a = c.children.find(p => p.code === area.value)
  if (a) {
    emits('change', { province: p.name, city: c.name, area: a.name })
  }
}
</script>

<style scoped>
</style>